<template>
  <view class="home-page">
    <!-- 顶部背景区域 -->
    <view class="header-bg">
      <!-- 用户信息区域 -->
      <view class="user-section">
        <view class="avatar-wrapper">
          <text class="avatar-text">{{ userInfo?.name?.slice(-2) || 'U' }}</text>
        </view>
        <view class="user-info">
          <text class="greeting">{{ greeting }}，{{ userInfo.name || '用户' }}</text>
          <u-tag
            color="white"
            borderColor="white"
            :text="userInfo.department || '阳卫'"
            type="info"
            plain
            size="mini"
          ></u-tag>
        </view>
      </view>

      <!-- 日期信息卡片 -->
      <view class="weather-card">
        <u-icon name="calendar" size="20" color="#fff"></u-icon>
        <text class="weather-text">{{ currentDateText }}</text>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 快捷服务网格 -->
      <view class="services-section">
        <view class="section-header">
          <text class="section-title">快速入口</text>
        </view>
        <u-grid :col="4" :border="false">
          <u-grid-item
            v-for="action in quickActions"
            :key="action.id"
            @click="handleAction(action)"
          >
            <view class="grid-item-content">
              <view class="service-icon" :style="{ background: action.bgColor }">
                <image
                  v-if="action.isImage"
                  class="icon-image"
                  :src="action.icon"
                  mode="aspectFit"
                />
                <u-icon v-else :name="action.icon" color="#ffffff" size="32"></u-icon>
              </view>
              <text class="service-name">{{ action.name }}</text>
            </view>
          </u-grid-item>
        </u-grid>
      </view>
      <!-- 我的待办 -->
      <view class="todo-section">
        <view class="section-header">
          <text class="section-title">我的待办</text>
        </view>

        <view class="todo-list" v-if="todoList.length > 0">
          <view class="todo-item" v-for="todo in todoList" :key="todo.id" @click="handleTodo(todo)">
            <view class="todo-item-left">
              <u-tag
                :text="todo.type"
                :type="getTodoTagType(todo.category)"
                size="mini"
                shape="circle"
              ></u-tag>
              <text class="todo-item-title">{{ todo.title }}</text>
            </view>
            <view class="todo-item-right">
              <text class="todo-item-time">{{ todo.createTime }}</text>
              <u-tag
                :text="getStatusText(todo.status)"
                :type="getStatusTagType(todo.status)"
                size="mini"
                plain
              ></u-tag>
            </view>
          </view>
        </view>

        <u-empty v-else mode="list" text="暂无待办事项">
          <template #bottom>
            <text class="empty-desc">您已完成所有待办任务</text>
          </template>
        </u-empty>
      </view>
      <!-- 系统公告 -->
      <view class="announcement-section">
        <view class="section-header">
          <!-- <u-icon name="volume" size="20"></u-icon> -->
          <text class="section-title">系统公告</text>
        </view>
        <u-cell-group class="notice-list" :border="false" v-if="announcements.length > 0">
          <u-cell
            v-for="announcement in announcements"
            :key="announcement.id"
            :title="announcement.title"
            :value="formatTime(announcement.publishTime || '')"
            :border="false"
            @click="viewAnnouncement(announcement)"
          >
            <template #icon>
              <u-icon name="volume-fill" size="18" color="#ff6b81"></u-icon>
            </template>
            <template #right-icon>
              <u-tag v-if="announcement.isNew" text="NEW" type="error" size="mini"></u-tag>
            </template>
          </u-cell>
        </u-cell-group>
      </view>
    </view>

    <!-- 自定义TabBar -->
    <CustomTabBar />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { UserManager } from '@/utils/user'
import { BadgeManager } from '@/utils/badge'
import CustomTabBar from '@/custom-tab-bar/index.vue'
import { getRoleNamesByUserId } from '@/Api/role'
import {
  getHomeAnnouncementList,
  getAnnouncementDetail,
  type AnnouncementInfo,
} from '@/Api/announcement'

// 用户信息
const userInfo = computed(() => {
  return (
    UserManager.getFullUserInfo() || {
      name: '用户',
      department: '办公室',
      id: null,
    }
  )
})

// 通知数量
const notificationCount = ref(3)

// 用户菜单权限
const userMenuPaths = ref<string[]>([])

// 问候语
const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 6) return '夜深了'
  if (hour < 9) return '早上好'
  if (hour < 12) return '上午好'
  if (hour < 14) return '中午好'
  if (hour < 18) return '下午好'
  if (hour < 22) return '晚上好'
  return '夜深了'
})

// 当前日期文本（包含星期）
const currentDateText = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  const day = now.getDate()
  const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const weekDay = weekDays[now.getDay()]

  return `${year}年${month}月${day}日 ${weekDay}`
})

// 检查用户是否有任一菜单权限
const hasAnyMenuPermission = (menuPaths: string[]): boolean => {
  return menuPaths.some((menuPath) => userMenuPaths.value.includes(menuPath))
}

// 所有快捷操作配置
const allQuickActions = [
  {
    id: 1,
    name: '登记收文',
    icon: 'plus-circle',
    color: '#1890ff',
    isImage: false,
    bgColor: 'linear-gradient(135deg, #c6e2ff 0%, #1890ff 100%)',
    path: '/pages/document/receive/darf/index',
    requiredMenuPaths: ['/receive/register', '/receive', '/receive/draft'],
  },
  {
    id: 2,
    name: '待办收文',
    icon: 'checkmark-circle',
    color: '#13C2C2',
    isImage: false,
    bgColor: 'linear-gradient(135deg, #b3e19d 0%, #13C2C2 100%)',
    path: '/pages/document/receive/todo/index',
    requiredMenuPaths: ['/receive/todo', '/receive'],
  },
  {
    id: 3,
    name: '发文审批',
    icon: 'share-square',
    color: '#faad14',
    isImage: false,
    bgColor: 'linear-gradient(135deg, #f8e3c5 0%, #faad14 100%)',
    path: '/pages/document/send/index?tab=todo',
    requiredMenuPaths: ['/document/todo', '/document/approval', '/document'],
  },
  {
    id: 4,
    name: '请假报备',
    icon: 'calendar',
    color: '#722ed1',
    isImage: false,
    bgColor: 'linear-gradient(135deg, #a8edea 0%, #722ed1 100%)',
    path: '/pages/leave/index',
    requiredMenuPaths: [], // 空数组表示任何人都可以访问
  },
]

// 根据权限过滤的快捷操作
const quickActions = computed(() => {
  // 如果还没有加载权限，返回所有不需要权限的操作（如请假管理）
  if (userMenuPaths.value.length === 0) {
    return allQuickActions.filter(
      (action) => !action.requiredMenuPaths || action.requiredMenuPaths.length === 0,
    )
  }

  // 根据用户菜单权限过滤显示的快速操作
  const filtered = allQuickActions.filter((action) => {
    // 如果 requiredMenuPaths 为空或不存在，表示任何人都可以访问
    if (!action.requiredMenuPaths || action.requiredMenuPaths.length === 0) {
      return true
    }
    // 检查是否拥有该功能所需的任一菜单权限
    const hasPermission = hasAnyMenuPermission(action.requiredMenuPaths)
    return hasPermission
  })
  return filtered
})

// 待办事项
const todoList = ref<any[]>([])

// 最近文档
const recentDocuments = ref<any[]>([])

// 缓存上次的角标数量（用于避免重复推送）
let lastBadgeCount = 0

// 系统公告
const announcements = ref<AnnouncementInfo[]>([])

// 处理快捷功能点击
const handleAction = (action: any) => {
  if (action.path) {
    uni.navigateTo({
      url: action.path,
      fail: () => {
        uni.showToast({
          title: '页面开发中',
          icon: 'none',
        })
      },
    })
  } else {
    uni.showToast({
      title: `点击了${action.name}`,
      icon: 'none',
    })
  }
}

// 显示用户信息
const showUserInfo = () => {
  uni.showToast({
    title: `${userInfo.value.name} - ${userInfo.value.department}`,
    icon: 'none',
  })
}

// 显示用户菜单
const showUserMenu = () => {
  uni.showActionSheet({
    itemList: ['个人设置', '退出登录'],
    success: (res) => {
      if (res.tapIndex === 1) {
        logout()
      }
    },
  })
}

// 处理待办事项
const handleTodo = (todo: any) => {
  // 根据待办类型跳转到不同的页面和tab
  let targetUrl = ''
  let tabName = ''

  switch (todo.todoType) {
    case 'approval':
      // 待审批 → 跳转到发文管理的"待审批"tab
      targetUrl = '/pages/document/send/index?tab=todo'
      tabName = '待审批'
      break
    case 'redHeader':
      // 待套红 → 跳转到发文管理的"套红"tab
      targetUrl = '/pages/document/send/index?tab=redHeader'
      tabName = '套红'
      break
    case 'seal':
      // 待签章 → 跳转到发文管理的"签章"tab
      targetUrl = '/pages/document/send/index?tab=seal'
      tabName = '签章'
      break
    case 'distribute':
      // 待分发 → 跳转到发文管理的"分发"tab
      targetUrl = '/pages/document/send/index?tab=distribute'
      tabName = '分发'
      break
    case 'receiveTodo':
    case 'receive':
      // 待办收文 → 跳转到待办收文页面
      targetUrl = '/pages/document/receive/todo/index'
      tabName = '待办收文'
      break
    case 'receiveRegister':
      // 登记收文 → 跳转到收文草稿页面，并切换到"登记收文"标签
      targetUrl = '/pages/document/receive/darf/index?filter=register'
      tabName = '登记收文'
      break
    case 'internalReceive':
      // 待阅发文 → 跳转到待阅发文页面
      targetUrl = '/pages/document/receive/read/index'
      tabName = '待阅发文'
      break
    case 'leaveApproval':
      // 请假审批 → 跳转到待我审批页面
      targetUrl = '/pages/leave/approvals/pending'
      tabName = '请假审批'
      break
    case 'leave':
      // 请假管理 → 跳转到请假管理首页
      targetUrl = '/pages/leave/index'
      tabName = '请假管理'
      break
    default:
      uni.showToast({
        title: `处理待办：${todo.title}`,
        icon: 'none',
      })
      return
  }

  if (targetUrl) {
    uni.navigateTo({
      url: targetUrl,
      success: () => {},
      fail: (err) => {
        uni.showToast({
          title: '页面开发中',
          icon: 'none',
        })
      },
    })
  }
}

// 查看所有待办
const viewAllTodos = () => {
  // 跳转到公文流转系统仪表板，查看所有待办
  uni.navigateTo({
    url: '/pages/document/dashboard/index',
    fail: () => {
      uni.showToast({
        title: '页面开发中',
        icon: 'none',
      })
    },
  })
}

// 查看文档
const viewDocument = (doc: any) => {
  uni.showToast({
    title: `查看文档：${doc.title}`,
    icon: 'none',
  })
}

// 查看所有文档
const viewAllDocuments = () => {
  uni.showToast({
    title: '查看所有文档',
    icon: 'none',
  })
}

// 查看公告
const viewAnnouncement = async (announcement: AnnouncementInfo) => {
  try {
    uni.showLoading({ title: '加载中...' })
    const res: any = await getAnnouncementDetail(announcement.id)
    uni.hideLoading()

    if (res.data?.code === 200 && res.data?.data) {
      const detail = res.data.data
      uni.showModal({
        title: detail.title,
        content: detail.content || '暂无内容',
        showCancel: false,
        confirmText: '知道了',
      })
    } else {
      // 如果获取失败，显示简单信息
      uni.showModal({
        title: announcement.title,
        content: announcement.content || '暂无详细内容',
        showCancel: false,
        confirmText: '知道了',
      })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '获取公告详情失败',
      icon: 'none',
    })
  }
}

// 显示通知
const showNotifications = () => {
  uni.showToast({
    title: '查看通知消息',
    icon: 'none',
  })
}

// 获取待办状态文本
const getStatusText = (status: string) => {
  const statusMap: any = {
    pending: '待处理',
    urgent: '紧急',
    completed: '已完成',
  }
  return statusMap[status] || '未知'
}

// 获取待办标签类型（uview-plus）
const getTodoTagType = (category: string): string => {
  const typeMap: Record<string, string> = {
    send: 'primary',
    receive: 'warning',
    leave: 'error',
    redHeader: 'warning',
    seal: 'error',
    distribute: 'success',
    internalReceive: 'info', // 待阅发文使用info（蓝色）
  }
  return typeMap[category] || 'primary'
}

// 获取状态标签类型（uview-plus）
const getStatusTagType = (status: string): string => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    urgent: 'error',
    completed: 'success',
  }
  return typeMap[status] || 'info'
}

// 获取文档状态文本
const getDocStatusText = (status: string) => {
  const statusMap: any = {
    draft: '草稿',
    reviewing: '审核中',
    approved: '已通过',
    rejected: '已拒绝',
  }
  return statusMap[status] || '未知'
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}/${month}/${day}`
}

// 加载公告列表
const loadAnnouncementList = async () => {
  try {
    const res: any = await getHomeAnnouncementList()

    if (res?.code === 200 && res?.data) {
      const list = res.data.records || []

      // 判断公告是否为 NEW（7天内发布的）
      const now = new Date().getTime()
      const sevenDays = 7 * 24 * 60 * 60 * 1000

      announcements.value = list.map((item: AnnouncementInfo) => {
        const publishTime = item.publishTime ? new Date(item.publishTime).getTime() : 0
        const isNew = now - publishTime <= sevenDays
        return {
          ...item,
          isNew,
        }
      })
    } else {
      announcements.value = []
    }
  } catch (error) {
    announcements.value = []
  }
}

// 退出登录
const logout = () => {
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清除用户信息
        UserManager.clearUserInfo()
        uni.removeStorageSync('token')
        uni.removeStorageSync('refreshToken')

        // 跳转到登录页
        uni.reLaunch({
          url: '/pages/login/login',
        })
      }
    },
  })
}

// 加载待办事项（整合多个来源，根据权限过滤）
const loadTodoList = async () => {
  try {
    const {
      getCurrentUserPendingDocuments,
      getCurrentRedHeaderDocuments,
      getCurrentSealDocuments,
    } = await import('@/Api/document')

    // 获取用户菜单权限（从 API 直接获取）
    let userMenuPaths: string[] = []
    try {
      const { getRoleNamesByUserId } = await import('@/Api/role')
      const menuResp = await getRoleNamesByUserId()

      if (menuResp.code === 200 && menuResp.data) {
        userMenuPaths = menuResp.data
      } else {
        // 使用默认权限（所有用户至少有查看待审批的权限）
        userMenuPaths = ['/document', '/document/draft', '/document/todo', '/document/distribute']
      }
    } catch (error) {
      // 异常情况，使用默认权限
      userMenuPaths = ['/document', '/document/draft', '/document/todo', '/document/distribute']
    }

    // 根据权限决定要查询的数据
    const promises: Promise<any>[] = []
    const types: string[] = []

    // 1. 待审批 - 检查是否有 /document/todo 或 /document/approval 权限
    if (userMenuPaths.includes('/document/todo') || userMenuPaths.includes('/document/approval')) {
      promises.push(getCurrentUserPendingDocuments(1, 10, undefined))
      types.push('approval')
    } else {
      promises.push(Promise.resolve({ code: 200, data: [] }))
      types.push('approval')
    }

    // 2. 待套红 - 检查是否有 /document/red-header 权限
    if (userMenuPaths.includes('/document/red-header')) {
      promises.push(getCurrentRedHeaderDocuments())
      types.push('redHeader')
    } else {
      promises.push(Promise.resolve({ code: 200, data: [] }))
      types.push('redHeader')
    }

    // 3. 待签章 - 检查是否有 /document/seal 权限
    if (userMenuPaths.includes('/document/seal')) {
      promises.push(getCurrentSealDocuments())
      types.push('seal')
    } else {
      promises.push(Promise.resolve({ code: 200, data: [] }))
      types.push('seal')
    }

    // 4. 待分发 - 检查是否有 /document/distribute 权限
    if (userMenuPaths.includes('/document/distribute')) {
      // 查询当前用户已完结且未分发的公文
      const { getAllDocumentsall } = await import('@/Api/document')
      const userInfo = (await import('@/utils/user')).UserManager.getFullUserInfo()
      const applicantId = userInfo.id ? Number(userInfo.id) : undefined
      promises.push(
        getAllDocumentsall({
          current: 1,
          size: 10,
          applicantId: applicantId,
          state: 0, // 已完结
          isDistributed: 0, // 未分发
        }),
      )
      types.push('distribute')
    } else {
      promises.push(Promise.resolve({ code: 200, data: [] }))
      types.push('distribute')
    }

    // 5. 待办收文 - 检查是否有 /receive/todo 或 /receive 权限
    if (userMenuPaths.includes('/receive/todo') || userMenuPaths.includes('/receive')) {
      const { getMyDistributesByRole } = await import('@/Api/receive')
      promises.push(getMyDistributesByRole())
      types.push('receiveTodo')
    } else {
      promises.push(Promise.resolve({ code: 200, data: [] }))
      types.push('receiveTodo')
    }

    // 6. 待阅发文 - 所有用户都可以查看（不需要权限校验）
    const { getMyInternalReceiveDocuments } = await import('@/Api/receive')
    promises.push(
      getMyInternalReceiveDocuments({
        pageNum: 1,
        pageSize: 10,
        isRead: 0, // 只查询未读的
      }),
    )
    types.push('internalReceive')

    // 7. 登记收文 - 查询待登记的收文（receiveStepOrder = 0）
    // 检查是否有收文相关权限
    if (userMenuPaths.includes('/receive/register') || userMenuPaths.includes('/receive')) {
      const { getReceiveRegisterPage } = await import('@/Api/receive')
      promises.push(
        getReceiveRegisterPage({
          pageNum: 1,
          pageSize: 10,
          receiveStepOrder: 0, // 待登记状态
        }),
      )
      types.push('receiveRegister')
    } else {
      promises.push(Promise.resolve({ code: 200, data: { records: [], total: 0 } }))
      types.push('receiveRegister')
    }

    // 8. 请假审批 - 所有用户都可以查看（不需要权限校验）
    const { getPendingLeaveApprovals } = await import('@/Api/leave')
    const currentUserInfo = (await import('@/utils/user')).UserManager.getFullUserInfo()
    const currentUserId = currentUserInfo.id ? Number(currentUserInfo.id) : undefined
    if (currentUserId) {
      promises.push(getPendingLeaveApprovals(currentUserId, 1, 10))
      types.push('leaveApproval')
    } else {
      promises.push(Promise.resolve({ code: 200, data: [] }))
      types.push('leaveApproval')
    }

    // 并行获取有权限的待办数据
    const [
      approvalResp,
      redHeaderResp,
      sealResp,
      distributeResp,
      receiveTodoResp,
      internalReceiveResp,
      receiveRegisterResp,
      leaveApprovalResp,
    ] = await Promise.all(promises)

    const allTodos: any[] = []

    // 1. 处理待审批数据
    if (approvalResp.code === 200 && approvalResp.data) {
      const approvalRecords = approvalResp.data.records || approvalResp.data || []
      approvalRecords.forEach((item: any) => {
        allTodos.push({
          ...item,
          todoType: 'approval', // 标记为待审批
          todoCategory: 'send',
          todoLabel: '待审批',
        })
      })
    }

    // 2. 处理待套红数据
    if (redHeaderResp.code === 200 && redHeaderResp.data) {
      const redHeaderList = redHeaderResp.data || []
      redHeaderList.slice(0, 3).forEach((item: any) => {
        // 只取前3条
        allTodos.push({
          ...item,
          todoType: 'redHeader', // 标记为待套红
          todoCategory: 'redHeader',
          todoLabel: '套红',
        })
      })
    }

    // 3. 处理待签章数据
    if (sealResp.code === 200 && sealResp.data) {
      const sealList = sealResp.data || []
      sealList.slice(0, 3).forEach((item: any) => {
        // 只取前3条
        allTodos.push({
          ...item,
          todoType: 'seal', // 标记为待签章
          todoCategory: 'seal',
          todoLabel: '签章',
        })
      })
    }

    // 4. 处理待分发数据
    if (distributeResp.code === 200 && distributeResp.data) {
      const distributeRecords = distributeResp.data.records || distributeResp.data || []
      distributeRecords.slice(0, 3).forEach((item: any) => {
        // 只取前3条
        allTodos.push({
          ...item,
          todoType: 'distribute', // 标记为待分发
          todoCategory: 'distribute',
          todoLabel: '分发',
        })
      })
    }

    // 5. 处理待办收文数据
    if (receiveTodoResp.code === 200 && receiveTodoResp.data) {
      const receiveTodoList = receiveTodoResp.data || []
      receiveTodoList.slice(0, 3).forEach((item: any) => {
        // 只取前3条
        allTodos.push({
          ...item,
          todoType: 'receiveTodo', // 标记为待办收文
          todoCategory: 'receive',
          todoLabel: '待办收文',
        })
      })
    }

    // 6. 处理待阅发文数据
    if (internalReceiveResp.code === 200 && internalReceiveResp.data) {
      const internalReceiveList = internalReceiveResp.data.records || internalReceiveResp.data || []
      internalReceiveList.slice(0, 3).forEach((item: any) => {
        // 只取前3条
        allTodos.push({
          ...item,
          todoType: 'internalReceive', // 标记为待阅发文
          todoCategory: 'internalReceive',
          todoLabel: '待阅发文',
        })
      })
    }

    // 7. 处理登记收文数据
    if (receiveRegisterResp.code === 200 && receiveRegisterResp.data) {
      const receiveRegisterList = receiveRegisterResp.data.records || receiveRegisterResp.data || []
      receiveRegisterList.slice(0, 3).forEach((item: any) => {
        // 只取前3条
        allTodos.push({
          ...item,
          todoType: 'receiveRegister', // 标记为登记收文
          todoCategory: 'receive',
          todoLabel: '登记收文',
        })
      })
    }

    // 8. 处理请假审批数据
    if (leaveApprovalResp.code === 200 && leaveApprovalResp.data) {
      const leaveApprovalList = leaveApprovalResp.data.records || leaveApprovalResp.data || []
      leaveApprovalList.slice(0, 3).forEach((item: any) => {
        // 只取前3条
        allTodos.push({
          ...item,
          todoType: 'leaveApproval', // 标记为请假审批
          todoCategory: 'leave',
          todoLabel: '请假审批',
          title: `${item.applicantName || '未知'} · ${item.reason || '请假'}`, // 组合标题
          createdAt: item.submitTime, // 使用提交时间
        })
      })
    }

    // 按创建时间排序，取最新的10条
    allTodos.sort((a, b) => {
      const timeA = new Date(a.createdAt || 0).getTime()
      const timeB = new Date(b.createdAt || 0).getTime()
      return timeB - timeA
    })

    const topTodos = allTodos.slice(0, 10)

    // 转换数据格式以适配模板
    todoList.value = topTodos.map((item: any) => {
      // 格式化时间为人性化显示
      let createTime = ''
      if (item.createdAt) {
        const date = new Date(item.createdAt)
        const now = new Date()
        const diffMs = now.getTime() - date.getTime()
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

        if (diffHours < 1) {
          createTime = '刚刚'
        } else if (diffHours < 24) {
          createTime = `${diffHours}小时前`
        } else if (diffDays < 7) {
          createTime = `${diffDays}天前`
        } else {
          createTime = `${date.getMonth() + 1}-${date.getDate()}`
        }
      }

      // 判断紧急状态
      let status = 'pending' // 默认待处理
      if (item.urgencyLevel === '特急' || item.urgencyLevel === '急件') {
        status = 'urgent'
      }

      return {
        id: item.id,
        category: item.todoCategory,
        type: item.todoLabel, // 显示"待审批"、"套红"、"签章"等
        todoType: item.todoType, // 用于点击跳转
        title: item.sourceDocumentTitle || item.title || '无标题', // 待办收文用 sourceDocumentTitle
        createTime: createTime,
        status: status,
        originalData: item,
      }
    })

    // 更新应用角标
    await updateBadge()
  } catch (error) {
    // 如果API调用失败，保持空数组
    todoList.value = []
    // 清除角标
    await BadgeManager.clearBadge()
  }
}

// 更新应用角标（智能推送）
const updateBadge = async () => {
  const newCount = todoList.value.length

  // 🔥 获取当前系统角标数量，确保同步
  const currentSystemBadge = BadgeManager.getCurrentBadge()

  // 如果角标数量没有变化，且系统角标也一致，才跳过更新
  // 这样可以避免从存储恢复的角标数量与待办列表不一致的问题
  if (newCount === lastBadgeCount && newCount === currentSystemBadge) {
    return
  }

  // 判断是增加还是减少
  const isIncrease = newCount > lastBadgeCount
  const change = newCount - lastBadgeCount

  console.log(
    `[updateBadge] 更新角标: ${lastBadgeCount} -> ${newCount} (系统当前: ${currentSystemBadge})`,
  )

  // 更新角标
  // silent: 静默更新（不创建通知）
  // - 用户主动返回查看：静默 ✅
  // - 待办减少（用户处理了）：静默 ✅
  // - 待办增加（可能是新分配）：也先静默，等服务端推送 ✅
  await BadgeManager.setBadge(newCount, {
    silent: true, // App打开时都静默，由服务端推送负责通知
    isIncrease: isIncrease,
  })

  // 更新缓存
  lastBadgeCount = newCount
}

// 加载用户菜单权限
const loadUserMenuPaths = async () => {
  try {
    const response = await getRoleNamesByUserId()
    if (response && response.code === 200) {
      userMenuPaths.value = response.data || []
    } else {
      userMenuPaths.value = []
    }
  } catch (error) {
    userMenuPaths.value = []
  }
}

// 用于防止重复加载的标志
let isFirstLoad = true

// 页面显示时（从其他页面返回）
onShow(() => {
  // 隐藏原生TabBar，显示自定义TabBar
  uni.hideTabBar({
    animation: false,
  })

  // 确保TabBar状态正确（特别是登录后首次进入）
  try {
    const { useTabBarStore } = require('@/stores/modules/tabbar')
    const tabBarStore = useTabBarStore()
    if (tabBarStore.currentIndex !== 0) {
      tabBarStore.setCurrentIndex(0)
    }
  } catch (error) {
    //
  }

  // 如果是首次加载，跳过（因为onMounted已经加载了）
  if (isFirstLoad) {
    isFirstLoad = false
    return
  }

  // 非首次加载时才刷新数据
  loadTodoList()
  loadAnnouncementList()
})

onMounted(async () => {
  await UserManager.ensureUserInfo()

  // 加载用户菜单权限
  await loadUserMenuPaths()

  // 请求推送权限（iOS需要）
  // #ifdef APP-PLUS
  const hasPermission = await BadgeManager.requestPushPermission()
  if (!hasPermission) {
    console.warn('[HomePage] 推送权限被拒绝，角标功能可能无法使用')
  }
  // #endif

  // 🔥 在加载待办列表之前，先同步 lastBadgeCount 和系统角标
  // 这样可以避免从存储恢复的角标数量与待办列表不一致的问题
  const currentSystemBadge = BadgeManager.getCurrentBadge()
  lastBadgeCount = currentSystemBadge
  console.log('[HomePage] 初始化角标数量:', currentSystemBadge)

  // 加载待办事项（仅加载一次）
  await loadTodoList()

  // 加载公告列表
  await loadAnnouncementList()
})
</script>

<style lang="scss" scoped>
.home-page {
  // height: calc(100vh - 50px);
  height: calc(100vh);
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

// 顶部背景区域
.header-bg {
  // background: url('http://111.53.165.56:8000/static/img/mobile/bj01.png') no-repeat center;
  background-size: cover;
  padding-bottom: 38rpx;
  position: relative;
  overflow: hidden;
  // background: linear-gradient(to right, #1a3582, #1890ff);
  background: linear-gradient(135deg, #1a3582 0%, #1890ff 100%);

  // 装饰圆圈
  &::before,
  &::after {
    content: '';
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }

  &::before {
    width: 300rpx;
    height: 300rpx;
    top: -100rpx;
    right: -80rpx;
  }
}

// 用户信息区域
.user-section {
  padding: 40px 30rpx 24rpx;
  display: flex;
  align-items: center;
  gap: 24rpx;
  position: relative;
  z-index: 2;

  .avatar-wrapper {
    width: 140rpx;
    height: 140rpx;
    border-radius: 70rpx;
    background: rgba(255, 255, 255, 0.25);
    border: 6rpx solid rgba(255, 255, 255, 0.4);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);

    .avatar-text {
      font-size: 48rpx;
      font-weight: bold;
      color: white;
      text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
    }

    .avatar-badge {
      position: absolute;
      bottom: 0;
      right: 0;
      background: linear-gradient(135deg, #ffd700, #ffed4e);
      color: #8b4513;
      font-size: 20rpx;
      font-weight: bold;
      padding: 4rpx 12rpx;
      border-radius: 20rpx;
      border: 3rpx solid white;
    }
  }

  .user-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 12rpx;

    .greeting {
      font-size: 36rpx;
      font-weight: bold;
      color: white;
      text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.15);
      letter-spacing: 1rpx;
    }
  }
}

// 天气卡片
.weather-card {
  margin: 0 30rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 20rpx;
  padding: 16rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
  backdrop-filter: blur(10rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  position: relative;
  z-index: 2;

  .weather-text {
    font-size: 26rpx;
    color: white;
    opacity: 0.9;
  }
}

// 主内容区域
.main-content {
  background: #f5f7fa;
  margin-top: -20rpx;
  border-radius: 30rpx 30rpx 0 0;
  padding: 40rpx 30rpx;
  position: relative;
  z-index: 3;
  flex: 1;
  overflow: auto;
}

// 服务网格
.services-section {
  margin-bottom: 40rpx;

  .section-header {
    margin-bottom: 28rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      position: relative;
      padding-left: 20rpx;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8rpx;
        height: 28rpx;
        background: linear-gradient(to bottom, #4facfe, #00f2fe);
        border-radius: 4rpx;
      }
    }
  }

  .grid-item-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;

    .service-icon {
      width: 100rpx;
      height: 100rpx;
      border-radius: 24rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);

      .icon-text {
        font-size: 40rpx;
      }

      .icon-image {
        width: 60rpx;
        height: 60rpx;
      }
    }

    .service-name {
      font-size: 24rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

// 横幅区域
.banner-section {
  margin-bottom: 40rpx;

  .banner-content-wrapper {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16rpx;
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      right: 0;
      width: 200rpx;
      height: 200rpx;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 50%;
      transform: translate(50%, -50%);
    }

    .banner-text {
      position: relative;
      z-index: 2;

      .banner-title {
        font-size: 32rpx;
        font-weight: bold;
        color: white;
        margin-bottom: 8rpx;
      }

      .banner-subtitle {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.8);
      }
    }

    .banner-icon {
      font-size: 60rpx;
      position: relative;
      z-index: 2;
    }
  }
}

// 待办事项区域
.todo-section {
  margin-bottom: 40rpx;

  .section-header {
    margin-bottom: 24rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      position: relative;
      padding-left: 20rpx;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8rpx;
        height: 28rpx;
        background: linear-gradient(to bottom, #722ed1, #d6cbe7);
        border-radius: 4rpx;
      }
    }
  }

  .todo-list {
    background: white;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);

    .todo-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16rpx 24rpx;
      border-bottom: 1rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      &:active {
        background: #f8f9fa;
      }

      .todo-item-left {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 12rpx;
        min-width: 0;

        .todo-item-title {
          flex: 1;
          font-size: 28rpx;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .todo-item-right {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 6rpx;
        flex-shrink: 0;
        margin-left: 16rpx;

        .todo-item-time {
          font-size: 22rpx;
          color: #999;
        }
      }
    }
  }

  .empty-desc {
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
  }
}

// 公告区域
.announcement-section {
  .section-header {
    margin-bottom: 24rpx;
    display: flex;
    align-items: center;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      padding-left: 20rpx;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8rpx;
        height: 28rpx;
        background: linear-gradient(to bottom, #f56c6c, #ebb563);
        border-radius: 4rpx;
      }
    }
  }

  .notice-list {
    background: white;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  }
}
</style>
